import Response from '../../utils/response.js';
import { selfApi, waterApi } from '../../utils/request.js';

export default async (ctx) => {
  try {
    const orgList = await selfApi.post('/webDataApi/sqlQuery/user', {
        sql: `SELECT ORG_CODE,ORG_ID,ORG_NAME,REGION_NUM,REGION_NAME FROM AGCLOUD.OPU_OM_ORG WHERE ORG_DELETED = 0 AND ORG_CODE like '%JIAGOUYI_FSSSWJ_%' ORDER BY REGION_NUM`
    });
    
    if (orgList.data && orgList.data.code == 200) {
        const orgListData = orgList.data.data

        const sqlArr = []
        orgListData.map(item => {
            sqlArr.push(`'${item.ORG_ID}'`)
        })
        const userOrgList = await selfApi.post('/webDataApi/sqlQuery/user', {
            sql: `SELECT USER_ID,ORG_ID FROM AGCLOUD.OPU_OM_USER_ORG WHERE ORG_ID IN (${sqlArr.join(',')})`
        });
        if (userOrgList.data && userOrgList.data.code == 200) {
            const userOrgListData = userOrgList.data.data

            const userSqlArr = []
            userOrgListData.map(item => {
                userSqlArr.push(`'${item.USER_ID}'`)
            })

            const userList = await selfApi.post('/webDataApi/sqlQuery/user', {
                sql: `SELECT USER_ID,USER_NAME,LOGIN_NAME FROM AGCLOUD.OPU_OM_USER WHERE USER_ID IN (${userSqlArr.join(',')})`
            })
            
            if (userList.data && userList.data.code == 200) {
                const userListData2 = []

                const telphoneReq = /^(((13[0-9]{1})|(14[0-9]{1})|(15[0-9]{1})|(16[0-9]{1})|(17[0-9]{1})|(18[0-9]{1})|(19[0-9]{1}))+\d{8})$/

                userList.data.data.map(item => {
                    if  (
                        telphoneReq.test(item.LOGIN_NAME) && 
                        item.LOGIN_NAME != '15915218102' &&
                        item.LOGIN_NAME != '13143188532' &&
                        item.LOGIN_NAME != '13169979370' 
                    ) {
                        const obj = userOrgListData.find(child => child['USER_ID'] == item['USER_ID'])
                        
                        if (obj) {
                            const orgObj = orgListData.find(child => child['ORG_ID'] == obj['ORG_ID'])
                            item['ORG_NAME'] = orgObj['ORG_NAME']
                            item['ORG_ID'] = orgObj['ORG_ID']
                            item['REGION_NAME'] = orgObj['REGION_NAME']
                            item['REGION_NUM'] = orgObj['REGION_NUM']
                        }
                        userListData2.push(item)
                    }
                })

                // 创建参数对象
                const userLoginParams = new URLSearchParams();
                
                // 添加默认参数
                userLoginParams.append('pageNum', 1);
                userLoginParams.append('pageSize', 999999999);
                userLoginParams.append('sTime', ctx.request.body.sTime);
                userLoginParams.append('eTime', ctx.request.body.eTime);
                // userLoginParams.append('sTime', '2025-03-21 00:00:00');
                // userLoginParams.append('eTime', '2025-03-21 16:07:44');
                userLoginParams.append('appliModule', '水环境应用');

                const userLoginRes = await waterApi.post('/awater/LoginAudit/listLoginBehaviorAndLog', userLoginParams, {
                    headers: {
                        token: ctx.headers.token,
                        'Content-Type': 'application/x-www-form-urlencoded'
                    }
                });
                
                const userLoginData = userLoginRes.data.content.list;

                userListData2.map(item => {
                    const arr = userLoginData.filter(child => child.userId === item.USER_ID) || []

                    item.loginCount = arr.length
                    if (arr.length) {
                        item.lastLoginTime = arr[0].loginTime
                    } else {
                        item.lastLoginTime = null
                    }
                })

                orgListData.map(item => {
                    item['登录人数'] = 0
                    item['登录次数'] = 0

                    const userArr2 = userListData2.filter(child => child.ORG_ID === item.ORG_ID) || []
                    
                    if (userArr2.length) {
                        const userArr3 = userArr2.filter(child => child.loginCount > 0)

                        let loginCount = 0
                        
                        if (userArr3.length) {
                            userArr3.map(child => {
                                loginCount += child.loginCount
                            })

                            item['登录人数'] = userArr3.length
                            item['登录次数'] = loginCount
                        }
                    }
                })
                
                ctx.body = Response.success({
                    list: userListData2,
                    orgListData
                })
            } else {
                ctx.body = Response.error('获取数据失败1')
            }
        }
    } else {
      console.error('获取数据失败2');
      ctx.body = Response.error('获取数据失败');
    }
  } catch (err) {
    console.error('请求失败:', err);
    ctx.body = Response.error('获取数据失败')
  }
};